#!/usr/bin/perl

use Foundation;

my $ARDAgentPath = "System/Library/CoreServices/RemoteManagement/ARDAgent.app/Contents/MacOS/ARDAgent";

if (-e "/usr/sbin/pkgutil" && $ARGV[2] eq "/") {
	my $fileInfoPlistString = `pkgutil --file-info-plist $ARDAgentPath`;
	if ($?) {
		print "Could not read file info for ARDAgent\n";
		exit(0);
	}
	
	my $fileInfoPlist = NSString->stringWithString_($fileInfoPlistString)->propertyList();
	if (!$fileInfoPlist || !$$fileInfoPlist) {
		print "Could not parse property result from pkgutil\n";
		exit(0);
	}
	
	my $pathInfoArray = $fileInfoPlist->objectForKey_("path-info");
	my $highest = 0; my $chosen = "";
	for (my $i = 0; $i < $pathInfoArray->count(); $i++) {
		my $pkgid = $pathInfoArray->objectAtIndex_($i)->objectForKey_("pkgid")->UTF8String();	
		my $date = $pathInfoArray->objectAtIndex_($i)->objectForKey_("install-time")->longValue();
		
		if ($date > $highest) { $highest = $date; $chosen = $pkgid; }
	}
	
	system("pkgutil", "--edit-pkg", $chosen, "--learn", $ARDAgentPath);
}